﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Meqs.Entity;
using Meqs.Entity.Parameters;
using Meqs.Entity.Views;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;

public partial class Credit_Teacher_ScoreInput_GoodTeacherInput : ScoreInputBasePage
{
    protected int historyId = 0;
    protected String teachCode = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            teachCode = Request.Params["TeacherCode"];
            string s = Request.Params["HistoryId"];
            if (!string.IsNullOrEmpty(s))
                int.TryParse(s, out historyId);

            BindHeadTable();
            //BindBodyTable();
            //ClientScript.RegisterStartupScript(GetType(), "script", "setTableHeight();", true);

        }
    }

    protected string ReportTitle
    {
        get
        {
            string title = "{0}{1} {2}{3}学分报表";

            int schoolYear = SchoolYear;
            int term = Term;
            if (SchoolYear == -1 || Term == -1)
            {
                ISchoolInfoLogic schLogic = Container<ISchoolInfoLogic>.Instance;
                SchoolInfo sch = schLogic.FindBySchoolMark(SchoolMark);
                schoolYear = sch.SchoolYear;
                term = sch.SchoolTerm;
            }
            string termStr = term == 1 ? "上学期" : "下学期";
            return string.Format(title, Common.ConvertSchoolYear(schoolYear), termStr, Cause == null ? "" : Cause.CauseName, Common.ReportDateType(3));
        }
    }

    protected static string ExcelFileName
    {
        get
        {
            string title = "{0}{1} {2}{3}学分报表";

            int schoolYear = SchoolYear;
            int term = Term;
            if (SchoolYear == -1 || Term == -1)
            {
                ISchoolInfoLogic schLogic = Container<ISchoolInfoLogic>.Instance;
                SchoolInfo sch = schLogic.FindBySchoolMark(SchoolMark);
                schoolYear = sch.SchoolYear;
                term = sch.SchoolTerm;
            }
            string termStr = term == 1 ? "上学期" : "下学期";
            return string.Format(title, Common.ConvertSchoolYear(schoolYear), termStr, Cause == null ? "" : Cause.CauseName, Common.ReportDateType(3));
        }
    }

    protected string ReportSubTitle
    {
        get
        {
            string title = "月份：{1}";
            IClsInfoLogic clsLogic = Container<IClsInfoLogic>.Instance;

            ClsInfo cls = clsLogic.FindById(ClsID);
            if (cls == null)
                cls = new ClsInfo();
            return string.Format(title, cls.ClsName, Year + "年" + Month + "月");
        }
    }

    private int _tableWidth;

    protected void BindHeadTable()
    {
        #region 绑定头
        _tableWidth = 0;

        ITeacherEvalTypeLogic mtLogic = Container<ITeacherEvalTypeLogic>.Instance;
        ITeacherEvalItemLogic miLogic = Container<ITeacherEvalItemLogic>.Instance;
        IList<TeacherEvalType> list;

        if (SchoolYear == -1 || Term == -1)
        {
            ISchoolInfoLogic schoolLogic = Container<ISchoolInfoLogic>.Instance;
            SchoolInfo schoolInfo = schoolLogic.FindBySchoolMark(SchoolMark);
            list = mtLogic.GetTeachHisType(SchoolMark, schoolInfo.SchoolYear, schoolInfo.SchoolTerm, HistoryId, "StuCause");
        }
        else
        {
            list = mtLogic.GetTeachHisType(SchoolMark, SchoolYear, Term, HistoryId, "StuCause");
        }

        Hashtable ht = new Hashtable();
        ht.Add("SchoolYear", SchoolCommon.Sch_SchoolInfo.SchoolYear);
        ht.Add("Term", SchoolCommon.Sch_SchoolInfo.SchoolTerm);
        IList<TermInfo> tinfoList = Container<ITermInfoLogic>.Instance.FindAll(ht);
        if (tinfoList == null || tinfoList.Count < 1)
            return;

        DateTime termStart = (DateTime)tinfoList[0].StartDate;
        IList<DateTime> dateList = new List<DateTime>();
        while (!(termStart.Month > DateTime.Now.Month && termStart > DateTime.Now))
        {
            dateList.Add(termStart);
            termStart = termStart.AddMonths(1);
        }

        TableRow row = new TableRow();
        TableRow subRow = new TableRow();
        row.Style["background-color"] = "#D4F1F9";
        subRow.Style["background-color"] = "#D4F1F9";

        TableCell cell1 = new TableCell();
        cell1.Text = "工号";
        cell1.RowSpan = 2;
        cell1.CssClass = "FixedRowCol";
        cell1.Style["width"] = "40px";
        row.Cells.Add(cell1);
        _tableWidth += 40;

        TableCell cell2 = new TableCell();
        cell2.Text = "姓名";
        cell2.RowSpan = 2;
        cell2.CssClass = "FixedRowCol";
        cell2.Style["width"] = "100px";
        row.Cells.Add(cell2);
        _tableWidth += 100;

        int index = 0;
        int scoreSumInMonthcellIndex = 0;
        foreach (TeacherEvalType mt in list)
        {
            TableCell cell = new TableCell();
            cell.Text = mt.Caption;
            IList<TeacherEvalItem> miList = miLogic.GetItemByType(SchoolMark, mt.RID);
            cell.ColumnSpan = miList.Count;
            cell.CssClass = "FixedRow";
            cell.Style["width"] = (60 * miList.Count) + "px";
            _tableWidth += 60 * miList.Count;

            // 学分录入 类的特殊处理
            if (cell.Text == "学分录入")
            {
                scoreSumInMonthcellIndex = index + 2;
                cell.ColumnSpan += dateList.Count;
                foreach (DateTime time in dateList)
                {
                    TableCell hcell = new TableCell();
                    hcell.Text = String.Format("{0}月", time.Month);
                    hcell.Style[HtmlTextWriterStyle.Width] = "60px";
                    _tableWidth += 60;
                    hcell.CssClass = "FixedRow";
                    subRow.Cells.Add(hcell);
                    index++;
                }
            }

            foreach (TeacherEvalItem item in miList)
            {
                TableCell subCell = new TableCell();
                subCell.Text = item.Caption + (item.Type == 1 ? String.Format("({0}分)", item.Param * item.Operator) : "(次)");
                subCell.CssClass = "FixedRow";
                subCell.Style["width"] = "60px";
                subCell.Attributes.Add("itemID", item.RID.ToString());
                subRow.Cells.Add(subCell);
                ParamVal pv = new ParamVal();
                pv.Index = index;
                pv.ItemID = item.RID;
                _paramVals.Add(pv);
                index++;
            }
            row.Cells.Add(cell);
        }
        TableCell cell3 = new TableCell();
        cell3.Text = "备注";
        cell3.RowSpan = 2;
        cell3.CssClass = "FixedRow";
        cell3.Style["width"] = "200px";
        row.Cells.Add(cell3);
        _tableWidth += 200;
        tblHead.Rows.Add(row);
        tblHead.Rows.Add(subRow);
        tblHead.Style["width"] = _tableWidth + "px";
        #endregion

        #region 绑定表格内容
        ITeacherEvalDetailLogic mdLogic = Container<ITeacherEvalDetailLogic>.Instance;
        ITeacherEvalRemarkLogic mrLogic = Container<ITeacherEvalRemarkLogic>.Instance;

        row = new TableRow();
        TableCell cellSNo = new TableCell();
        cellSNo.Style["border-top"] = "0px";
        cellSNo.Text = teachCode;
        cellSNo.CssClass = "FixedCol";
        cellSNo.Style["width"] = "40px";
        cellSNo.Style["text-align"] = "right";
        row.Cells.Add(cellSNo);

        TableCell cellSName = new TableCell();
        cellSName.Style["border-top"] = "0px";
        cellSName.CssClass = "FixedCol";
        cellSName.Text = "&nbsp;" + TeacherName;
        cellSName.Style["width"] = "100px";
        cellSName.Style["text-align"] = "left";
        row.Cells.Add(cellSName);


        IList<TeacherInputEntity> sieList = mdLogic.GetTeacherInputEntityByTerm(HistoryId, EvalTeacherID, Year, Month, SchoolYear, Term, SchoolMark);
        IList<ParamVal> pvList = new List<ParamVal>();
        foreach (TeacherInputEntity item in sieList)
        {
            ParamVal pv = new ParamVal();
            pv.ItemID = item.ItemID;
            if (!_paramVals.Contains(pv)) continue;
            ParamVal p = _paramVals[_paramVals.IndexOf(pv)];
            p.Type = item.Type;
            p.Param = item.Param;
            p.Score = item.Score;
            p.Operator = item.Operator;
            pvList.Add(p);
        }
        ListSort<ParamVal> sort = new ListSort<ParamVal>(pvList, "Index", true);
        pvList = sort.Sort();
        int cellIndex = 0;
        foreach (ParamVal pv in pvList)
        {
            TableCell subCell;
            if((scoreSumInMonthcellIndex - 2) == cellIndex)
            {
                foreach (DateTime time in dateList)
                {
                    subCell = new TableCell();
                    subCell.Style["border-top"] = "0px";
                    subCell.Style["width"] = "60px";
                    subCell.Text = "";
                    subCell.Attributes.Add("DataMonth", time.Month.ToString());
                    row.Cells.Add(subCell);
                    cellIndex++;
                }    
            }

            subCell = new TableCell();
            subCell.Style["border-top"] = "0px";

            subCell.Style["width"] = "60px";
            // 计次
            if (pv.Type == 2)
            {
                // 可编辑状态
                if (IsModify)
                {
                    string html = string.Format(ScoreInputNumericHtmlStr, "txt_" + pv.ItemID + "_" + EvalTeacherID + "_2", pv.Param == 0 ? "" : pv.Param.ToString(), pv.Score, pv.Operator);
                    subCell.Text = html;
                    subCell.Attributes.Add("onmouseover", "try{mover(this);}catch(e){}");
                    subCell.Attributes.Add("onmouseout", "try{mout(this);}catch(e){}");
                }
                else
                {
                    subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
                    subCell.Style["text-align"] = "right";
                }
            }
            // 计分
            if (pv.Type == 1)
            {
                // 可编辑状态 
                if (IsModify)
                {
                    string html = string.Format(ScoreInputScoreHtmlStr, "txt_" + pv.ItemID + "_" + EvalTeacherID + "_1", pv.Param == 0 ? "" : pv.Param.ToString(), pv.Score);
                    subCell.Text = html;
                }
                else
                {
                    subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
                    subCell.Style["text-align"] = "right";
                }
            }
            cellIndex++;
            row.Cells.Add(subCell);
        }
        tblHead.Rows.Add(row);
        tblHead.Style["width"] = _tableWidth + "px";

        // 备注
        TeacherEvalRemark mr = mrLogic.GetRemarkByTeacher(HistoryId, EvalTeacherID, 0, 4, Year, Month, SchoolYear, Term, SchoolMark);
        TableCell cellRemark = new TableCell();
        cellRemark.Style["border-top"] = "0px";
        string span = "&nbsp;<span id=\"span_{0}\" title=\"{1}\">{2}</span>";
        span = string.Format(span, EvalTeacherID, mr == null ? "" : mr.Data, mr == null ? "" : mr.Data.Length > 20 ? mr.Data.Substring(0, 20) + "..." : mr.Data);
        cellRemark.Text = span;
        cellRemark.Attributes.Add("TeacherID", EvalTeacherID.ToString());
        cellRemark.Attributes.Add("TeacherName", TeacherName);
        if (IsModify) cellRemark.Attributes.Add("onclick", "displayRemark(this)");
        cellRemark.Style["width"] = "200px";
        cellRemark.Style["text-align"] = "left";
        row.Cells.Add(cellRemark);
        tblHead.Rows.Add(row);
        #endregion
    }

    //protected void BindBodyTable()
    //{
    //    ITeacherInfoLogic sLogic = Container<ITeacherInfoLogic>.Instance;
    //    ITeacherEvalDetailLogic mdLogic = Container<ITeacherEvalDetailLogic>.Instance;
    //    ITeacherEvalRemarkLogic mrLogic = Container<ITeacherEvalRemarkLogic>.Instance;

    //    TableRow row = new TableRow();
    //    TableCell cellSNo = new TableCell();
    //    cellSNo.Style["border-top"] = "0px";
    //    cellSNo.Text = 1 + "&nbsp;";
    //    cellSNo.CssClass = "FixedCol";
    //    cellSNo.Style["width"] = "40px";
    //    cellSNo.Style["text-align"] = "right";
    //    row.Cells.Add(cellSNo);

    //    TableCell cellSName = new TableCell();
    //    cellSName.Style["border-top"] = "0px";
    //    cellSName.CssClass = "FixedCol";
    //    cellSName.Text = "&nbsp;" + TeacherName;
    //    cellSName.Style["width"] = "100px";
    //    cellSName.Style["text-align"] = "left";
    //    row.Cells.Add(cellSName);


    //    IList<TeacherInputEntity> sieList = mdLogic.GetTeacherInputEntityByMonth(HistoryId, EvalTeacherID, 3, Year, Month, SchoolYear, Term, SchoolMark);
    //    IList<ParamVal> pvList = new List<ParamVal>();
    //    foreach (TeacherInputEntity item in sieList)
    //    {
    //        ParamVal pv = new ParamVal();
    //        pv.ItemID = item.ItemID;
    //        if (!_paramVals.Contains(pv)) continue;
    //        ParamVal p = _paramVals[_paramVals.IndexOf(pv)];
    //        p.Type = item.Type;
    //        p.Param = item.Param;
    //        p.Score = item.Score;
    //        p.Operator = item.Operator;
    //        pvList.Add(p);
    //    }
    //    ListSort<ParamVal> sort = new ListSort<ParamVal>(pvList, "Index", true);
    //    pvList = sort.Sort();
    //    foreach (ParamVal pv in pvList)
    //    {
    //        TableCell subCell = new TableCell();
    //        subCell.Style["border-top"] = "0px";

    //        subCell.Style["width"] = "60px";
    //        // 计次
    //        if (pv.Type == 2)
    //        {
    //            // 可编辑状态
    //            if (IsModify)
    //            {
    //                string html = string.Format(ScoreInputNumericHtmlStr, "txt_" + pv.ItemID + "_" + EvalTeacherID + "_2", pv.Param == 0 ? "" : pv.Param.ToString(), pv.Score, pv.Operator);
    //                subCell.Text = html;
    //                subCell.Attributes.Add("onmouseover", "mover(this);");
    //                subCell.Attributes.Add("onmouseout", "mout(this);");
    //            }
    //            else
    //            {
    //                subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
    //                subCell.Style["text-align"] = "right";
    //            }
    //        }
    //        // 计分
    //        if (pv.Type == 1)
    //        {
    //            // 可编辑状态 
    //            if (IsModify)
    //            {
    //                string html = string.Format(ScoreInputScoreHtmlStr, "txt_" + pv.ItemID + "_" + EvalTeacherID + "_1", pv.Param == 0 ? "" : pv.Param.ToString());
    //                subCell.Text = html;
    //            }
    //            else
    //            {
    //                subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
    //                subCell.Style["text-align"] = "right";
    //            }
    //        }

    //        row.Cells.Add(subCell);
    //    }
    //    tblHead.Rows.Add(row);
    //    tblHead.Style["width"] = _tableWidth + "px";

    //    // 备注
    //    TeacherEvalRemark mr = mrLogic.GetRemarkByTeacher(HistoryId, EvalTeacherID, 0, 3, Year, Month, SchoolYear, Term, SchoolMark);

    //    //     StuCauseEvalRemark mr = mrLogic.GetRemarkByStudent(info.RID, CauseID, 3, Year, Month, SchoolYear, Term, SchoolMark);
    //    TableCell cellRemark = new TableCell();
    //    //if (j == 0) 
    //    cellRemark.Style["border-top"] = "0px";
    //    string span = "&nbsp;<span id=\"span_{0}\" title=\"{1}\">{2}</span>";
    //    span = string.Format(span, EvalTeacherID, mr == null ? "" : mr.Data, mr == null ? "" : mr.Data.Length > 20 ? mr.Data.Substring(0, 20) + "..." : mr.Data);
    //    cellRemark.Text = span;
    //    cellRemark.Attributes.Add("TeacherID", EvalTeacherID.ToString());
    //    cellRemark.Attributes.Add("TeacherName", TeacherName);
    //    if (IsModify) cellRemark.Attributes.Add("onclick", "displayRemark(this)");
    //    cellRemark.Style["width"] = "200px";
    //    cellRemark.Style["text-align"] = "left";
    //    row.Cells.Add(cellRemark);
    //    tblHead.Rows.Add(row);
    //    tblHead.Style["width"] = _tableWidth + "px";

    //}

    /// <summary>
    /// 保存单据
    /// </summary>
    /// <param name="jsonStr"></param>
    /// <param name="causeID"></param>
    /// <param name="clsID"></param>
    /// <param name="schoolYear"></param>
    /// <param name="term"></param>
    /// <param name="year"></param>
    /// <param name="month"></param>
    /// <returns></returns>
    [WebMethod]
    public static bool SaveScoreInput(int historyId, string jsonStr, int schoolYear, int term, int year, int month)
    {
        try
        {
            IList<VItems> list = ConvertJson(jsonStr);

            int? syear = schoolYear == -1 ? (int?)null : schoolYear;
            int? sterm = term == -1 ? (int?)null : term;

            ITeacherEvalSubmitRecordLogic scesrLogic = Container<ITeacherEvalSubmitRecordLogic>.Instance;
            return scesrLogic.SaveOrUpdateRecord(list, historyId, 4, year, month, syear, sterm, 0, SchoolMark);
        }
        catch (Exception e)
        {

            throw;
        }
    }

    private static IList<VItems> ConvertJson(string jsonStr)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        return jss.Deserialize<IList<VItems>>(jsonStr);
    }
    protected void btnReflesh_Click(object sender, EventArgs e)
    {
        tblHead.Rows.Clear();
        tblHead.Rows.Clear();
        BindHeadTable();
        ///BindBodyTable();
    }

    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells, int causeID)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "\\download\\" + ExcelFileName + ".xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, ConvertToCause(causeID) + "学分报表", 2, 0, cells);
        return "";
    }

    [WebMethod]
    public static IList<StupidDemand> GetAStupidDemand(int teacherID)
    {
        Hashtable ht = new Hashtable();
        ht.Add("SchoolYear", SchoolCommon.Sch_SchoolInfo.SchoolYear);
        ht.Add("Term", SchoolCommon.Sch_SchoolInfo.SchoolTerm);
        IList<TermInfo> tinfoList = Container<ITermInfoLogic>.Instance.FindAll(ht);
        if (tinfoList == null || tinfoList.Count < 1)
            return null;
        return Container<ITeacherEvalHistoryLogic>.Instance.MakeAStupidDemand(tinfoList[0].SchoolYear, tinfoList[0].Term, teacherID, SchoolMark);
    }

    private static string ConvertToCause(int causeID)
    {
        return Container<IGlobalCauseInfoLogic>.Instance.FindById(causeID).CauseName;
    }
}
